Ext.ns('ru.proburo.oms.order.components.grid');

/**
 * @class ru.proburo.oms.order.components.grid.EditableList
 * @extends ru.proburo.oms.components.grid.AbstractEditableList
 */
ru.proburo.oms.order.components.grid.EditableList = Ext.extend(ru.proburo.oms.components.grid.AbstractEditableList, {
    
	_valid: true,
	_dirty: false,
	
    constructor: function(config)
	{
		config = config || {};
		
		this.store =  new ru.proburo.oms.order.dao.OrderLineStore();
		this.store.setOrderID(config.record.data.id);
		
		this.mStore = new ru.proburo.oms.order.dao.MultiplicityStore();
		
		Ext.ux.grid.GroupSummary.Calculations['Total'] = function(v, record, field){
			return v + (record.data.price * record.data.amount);
		};
		
		Ext.applyIf(config, {
			sm: new Ext.grid.CheckboxSelectionModel(),
			view: new Ext.grid.GroupingView({
				forceFit: 			true,
				showGroupsText: 	false,
				showGroupName: 		false,
				enableNoGroups: 	false,
				enableGroupingMenu: false,
				hideGroupedColumn: 	true
			}),
			plugins: new Ext.ux.grid.GroupSummary()
        });
        
        ru.proburo.oms.order.components.grid.EditableList.superclass.constructor.call(this, config);
    },
	
	initComponent: function()
	{
        ru.proburo.oms.order.components.grid.EditableList.superclass.initComponent.call(this);
		
		if(false === this.record.phantom)
        {
            this.store.load();
        }
	},
	
	initEvents: function()
	{
		this.addEvents({
            'change' : 		   true,
			'save' : 		   true,
			'selectionchange': true
        });
		
		this.relayEvents(this.getStore(), 		   ['save']);
		this.relayEvents(this.getSelectionModel(), ['selectionchange']);
		
		this.on('validateedit', function(e){
			this._validateRows();
			this._setModified(true);
		}, this);
		
		//this.getColumnModel().setEditable(5, !this.readonly);
		
		this.getStore().on({
			'load':	  this._validateLoad,
			'add': 	  this._validateAdd,
			'update': this._validateUpdate,
			scope: this
		});
		
		/*this.getView().on({
			'rowremoved': 	this._refreshSummary,
			'rowsinserted': this._refreshSummary,
			'rowupdated': 	this._refreshSummary,
			scope: this
		});*/
		/*this.store.add(new this.store.recordType({
			order_id: this.record.data.id,
			item_id: 275
		}));*/
		
		
		
		/*this.getView().on({
			'rowsinserted': this._loadMultiplicity,
			'rowupdated': 	this._loadMultiplicity,			
			scope: this
		});
		//this.form.customerField.on('change', this._loadMultiplicity);
		
		
		
		this.on('beforeedit', function(e){
			if(undefined !== (r = this.mStore.getById(e.record.data.id)))
			{
				console.log(e.record.data.id, r.data.multiplicity);
				
				this.spinnerField.minValue = r.data.multiplicity;
				Ext.apply(this.spinnerField.spinner, {
					incrementValue: 		 r.data.multiplicity,
					alternateIncrementValue: r.data.multiplicity * 4
				});
				
				this.spinnerField.on('show', function(f){
					if(0 !== (f.getValue() % f.minValue))
					{
						f.markInvalid('Minimum ammount: ' + f.minValue);
					}
				}, this, {single: true});
			}
		}, this);*/
		
		ru.proburo.oms.order.components.grid.EditableList.superclass.initEvents.call(this);
	},
	
	initColumns: function()
	{
		this.spinnerField = new ru.proburo.oms.order.components.form.Spinner({
			style: 'text-align: left;'
		});
        
		return [
			{
				id: 	   'order_id',
				header:    'order_id',
				dataIndex: 'order_id'
			},
			{
				id: 	   'sku',
				dataIndex: 'sku',
				header:    'Код',
				width: 	   10,
				sortable:  true
			},
			{
				id: 	   'name',
				dataIndex: 'name',
				header:    'Наименование товара',
				width: 	   50,
				sortable:  true
			},
			{
				id: 	   'vendor',
				dataIndex: 'vendor',
				header:    'Производитель',
				width: 	   15,
				sortable:  true
			},
			{
				id: 	   'article',
				dataIndex: 'article',
				header:    'Артикул',
				width: 	   15,
				sortable:  true
			},
			{
				id: 	   'amount',
				dataIndex: 'amount',
				header:    'Кол-во',
				width: 	   10,
				sortable:  true,
				
				editor:    this.spinnerField
			},
			{
				id: 	   'price',
				dataIndex: 'price',
				header:    'Цена, руб.',
				width: 	   10,
				sortable:  true,
				
				renderer:  		 Ext.util.Format.ruMoney,
				summaryRenderer: this._totalLabelRenderer
			},
			{
				id: 	   'summ',
				dataIndex: 'summ',
				header:    'Сумма, руб.',
				width: 	   10,
				sortable:  false,
				
				renderer: 		 function(value, metaData, record, rowIndex, colIndex, store)
				{
					return Ext.util.Format.ruMoney(record.data.price * record.data.amount);
				},
				summaryType: 	 'Total',
				summaryRenderer: this._totalRenderer
			}
		];
	},
	
	isValid: function()
	{
		return this._valid;
	},
	
	isDirty: function()
	{
		return this._dirty;
	},
	
	save: function(callback, scope)
	{
        if(callback)
		{
            this.on('save', callback, scope, {single:true});
        }
		
		this._setModified(false);
		
		var summ = 0;
		
		this.store.each(function(r){
			r.set('order_id', this.record.id);
			summ += r.get('price') * r.get('amount');
		}, this);
		
		this.record.set('summ', summ);
		// FIX
		//this.record.store.save();
		
		this.store.save();
	},
	
	addRecord: function(record)
	{
		var data  = (record instanceof Ext.data.Record) ? record.data : record;
		var store = this.getStore();
		
		if(store.findExact('sku', data.sku) < 0)
		{
			store.add(new store.recordType({
				item_id:  data.id,
				order_id: this.record.id,
				sku: 	  data.sku,
				name: 	  data.name,
				vendor:   data.vendor,
				article:  data.article,
				price: 	  data.price,
				amount:   data.amount || 1
			}));
		}
		
		this._setModified(true);
	},
	
	addRecords: function(records)
	{
		for(var i in records)
		{
			if(false === records.hasOwnProperty(i)){ continue; }
			
			this.addRecord(records[i]);
		}
	},
    
	
	
    removeSelected: function()
    {
        var sm = this.getSelectionModel();
		
		this.store.remove(sm.getSelections());
		
		sm.clearSelections();
		
		this._setModified(true);
    },
	
	setCustomer: function(customer)
	{
		this.customer = customer;
		//this.fireEvent('customer-change');
	},
	
	/**
	 * Renderers
	 */
	// private
    _totalLabelRenderer: function()
	{
		return '<div style="position: relative; font-weight: 600;">Всего к оплате:</div>';
	},
    
	// private
    _totalRenderer: function(value, metaData, record, rowIndex, colIndex, store)
    {
        return '<b>' + Ext.util.Format.ruMoney(value) + '</b>';
    },
	
	
	
	
	
	
	
	
	
	// private
	_setModified: function(modified)
	{
		if(this._dirty !== modified)
		{
			this._dirty = modified;
			
			this.fireEvent('change', this);
		}
	},
	
	// private
	_refreshSummary: function()
	{		
		var t = this.totalValue = 0.00;
		
		this.store.data.each(function(r){
			t += r.data.price * r.data.amount;
		});
		
		this.summTpl.setText('<b>Всего к оплате:&nbsp;&nbsp;</b>' + Ext.util.Format.ruMoney(t));
	},
	
	
	
	
	
	
	
	
	
	
	
	_validateLoad: function(store, records)
	{
		if(store.data.keys.length > 0)
		{
			this.mStore.on('load', this._validateRows, this, {single: true});
			
			var keys = [];
			
			store.data.each(function(record, key){
				
				keys.push(record.data.item_id);
				
			}, this);
			
			this.mStore.load('РЕГЗ', keys);
		}
	},
	
	_validateAdd: function(store, record, operation)
	{
		if(store.data.keys.length > 0)
		{
			this.mStore.on('load', this._validateRows, this, {single: true});
			
			this.mStore.load('РЕГЗ', store.data.keys);
		}
	},
	
	_validateUpdate: function(store, record, operation)
	{
		if(store.data.keys.length > 0)
		{
			this.mStore.on('load', this._validateRows, this, {single: true});
			
			this.mStore.load('РЕГЗ', store.data.keys);
		}
	},
	
	_validateMultiplicity: function()
	{
		this._valid = true;
		
		if(this.store.data.keys.length > 0)
		{
			this.mStore.on('load', this._validateRows, this, {single: true});
			this.mStore.load('РЕГЗ', this.store.data.keys);
		}
	},
	
	_validateRows: function(store, records, options)
	{
		this.mStore.data.each(this._validateRow, this);
	},
	
	_validateRow: function(row)
	{
		var record   = this.getStore().getById(row.data.item_id);
		var rowIndex = this.store.data.keys.indexOf(row.data.item_id);
		var rEl      = this.getView().getRow(rowIndex);
		var cEl      = rEl.getElementsByTagName('td')[5];
		
		if(0 !== record.data.amount % row.data.multiplicity)
		{
			this._markInvalid(rEl, cEl, row.data.multiplicity);
			
			this._valid = false;
		}
		else
		{
			this._clearInvalid(rEl, cEl);
		}
	},
	
	_markInvalid: function(row, cell, mux)
	{
		if(!cell.invalidMsg)
		{
			//Ext.fly(row).addClass('x-grid3-row-invalid');
			Ext.fly(cell).addClass('x-grid3-cell-invalid');
			cell.invalidMsg = new Ext.ToolTip({
				html:   '<b>Количество не кратно ' + mux + '</b>',
				target: cell
			});
		}
	},
	
	_clearInvalid: function(row, cell)
	{
		if(cell.invalidMsg)
		{
			Ext.fly(row).removeClass('x-grid3-row-invalid');
			Ext.fly(cell).removeClass('x-grid3-cell-invalid');
			cell.invalidMsg.destroy();
		}
	}
});